<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\BlindBoxOrder;
use App\Services\Cache\BlindBoxCache;
use App\Http\Controllers\Api\V1\Resources\BoxResource;
use App\Http\Controllers\Api\V1\Resources\BoxLevelResource;
use App\Http\Controllers\Api\V1\Resources\BoxProductResource;
use App\Http\Controllers\Api\V1\Resources\BoxOrderResource;
use App\Http\Controllers\Api\V1\Resources\BoxTakeOrderResource;
use App\Services\MakeBoxProductOrder\MakeBoxProductOrderRequest;
use App\Services\MakeBoxProductOrder\refreshBoxProductOrderRequest;
use App\Services\MakeBoxProductOrder\takeBoxProductOrderRequest;
use App\Services\MakeBoxProductOrder\MakeBoxProductOrder;
use App\Services\MakeBoxProductOrder\RefreshBoxProductOrder;
use App\Services\MakeBoxProductOrder\takeBoxProductOrder;

class BoxesController extends Controller
{
	public function index()
	{
		$boxes = app(BlindBoxCache::class)->boxes();
		return BoxResource::collection($boxes);
	}

	public function show($id)
	{
		$box = app(BlindBoxCache::class)->box($id);
		return new BoxResource($box);
	}

	public function levels($id)
	{
		$levels = app(BlindBoxCache::class)->levels($id);
	
		return BoxLevelResource::collection($levels);
	}

	public function takeOrders($id)
	{
		$orders = app(BlindBoxCache::class)->takeOrders($id);

		return BoxTakeOrderResource::collection($orders);
	}


	public function products($id)
	{
		$products = app(BlindBoxCache::class)->products($id);
		return BoxProductResource::collection($products);
	}

	public function store(MakeBoxProductOrderRequest $request)
    {

    	$order = app(MakeBoxProductOrder::class, [
		    'user' => $request->user(),
		    'address' => $request->getAddress(),
		    'blindBox' => $request->getBlindBox(),
		    'userCouponId' => request('user_coupon_id') ?? 0
	    ])->make();

    	return new BoxOrderResource($order);
    }

    public function orders()
	{
		$orders = request()->user()->blindBoxOrders()->whereNotNull('paid_at')->paginate();

		return BoxOrderResource::collection($orders);
	}

	public function order($id)
	{
		$order = request()->user()->blindBoxOrders()->where('id',$id)->first();

		return new BoxOrderResource($order);
	}

	public function refresh(RefreshBoxProductOrderRequest $request)
    {
    	
    	$order = app(RefreshBoxProductOrder::class, [
		    'user' => $request->user(),
		    'order' => $request->getBlindBoxOrder(),
	    ])->refresh();

	    return response(null, 204);
    }

    public function take(takeBoxProductOrderRequest $request)
    {
    	$order = app(takeBoxProductOrder::class, [
		    'user' => $request->user(),
		    'address' => $request->getAddress(),
		    'order' => $request->getBlindBoxOrder(),
	    ])->take();

	    return response(null, 204);
    }
}
